package com.example.sourcecodelearning.proxy.factory;

import cn.hutool.core.date.StopWatch;
import cn.hutool.core.lang.Console;
import lombok.AllArgsConstructor;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

/**
 * @author yuzhenxin
 * @date 2023-07-30 12:20
 */
@AllArgsConstructor
public class CglibProxy implements MethodInterceptor {

    @Override
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
        // obj是代理后的子类，也就是CEO$$EnhancerByCGLIB$$26b15a34
        // proxy是代理对象

        StopWatch stopWatch = new StopWatch("Cglib动态代理任务");

        System.out.printf("准备执行Cglib动态代理，方法%s\n", method.getName());
        stopWatch.start();

        // 进入 FastClass 的 invoke()，跟进方法索引找到obj的meeting()
        // 此时再执行 super.meeting();
        Object ret = proxy.invokeSuper(obj, args);

        System.out.printf("Cglib动态代理执行完成，方法%s\n", method.getName());
        stopWatch.stop();

        Console.log("任务执行耗时：{}毫秒", stopWatch.getTotal(TimeUnit.MILLISECONDS));

        return ret;
    }
}
